<template>
  <view class="audit-container">
    <!-- 统计卡片 -->
    <view class="stat-cards">
      <view class="stat-card">
        <view class="stat-value">{{ statistics.pending }}</view>
        <view class="stat-label">待审核</view>
      </view>
      <view class="stat-card">
        <view class="stat-value">{{ statistics.today }}</view>
        <view class="stat-label">今日审核</view>
      </view>
      <view class="stat-card">
        <view class="stat-value">{{ statistics.passed }}</view>
        <view class="stat-label">已通过</view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-box">
      <uni-search-bar 
        v-model="searchValue" 
        placeholder="搜索商户名称或预约编号" 
        @confirm="handleSearch"
        @clear="handleClear"
      ></uni-search-bar>
    </view>

    <!-- 筛选标签 -->
    <view class="filter-tabs">
      <view 
        v-for="(item, index) in filterTabs" 
        :key="index"
        :class="['filter-tab', { active: currentTab === item.value }]"
        @click="handleTabChange(item.value)"
      >
        {{ item.label }}
        <view v-if="item.count > 0" class="tab-badge">{{ item.count }}</view>
      </view>
    </view>

    <!-- 列表内容 -->
    <scroll-view 
      scroll-y 
      class="list-container"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="list.length > 0">
        <view v-for="item in list" :key="item.applyId" class="audit-item" @click="goToDetail(item)">
          <view class="item-header">
            <view class="item-title">{{ item.merchantName }}</view>
            <view :class="['item-status', getStatusClass(item.auditStatus)]">
              {{ getStatusText(item.auditStatus) }}
            </view>
          </view>
          
          <view class="item-info">
            <view class="info-row">
              <text class="info-label">预约编号：</text>
              <text class="info-value">{{ item.applyNo }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">入场时间：</text>
              <text class="info-value">{{ item.entryTime }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">车牌号：</text>
              <text class="info-value">{{ item.vehicleNo }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">入场地点：</text>
              <text class="info-value">{{ item.entryPlace }}</text>
            </view>
          </view>

          <view class="item-footer">
            <view class="submit-time">
              <uni-icons type="calendar" size="14" color="#999"></uni-icons>
              <text>提交时间：{{ formatTime(item.createTime) }}</text>
            </view>
            <view v-if="item.auditStatus === '0'" class="action-buttons">
              <view class="action-btn reject-btn" @click.stop="handleReject(item)">
                <uni-icons type="closeempty" size="18" color="#fff"></uni-icons>
                <text>拒绝</text>
              </view>
              <view class="action-btn inspect-btn" @click.stop="handleInspect(item)">
                <uni-icons type="eye-filled" size="18" color="#fff"></uni-icons>
                <text>抽检</text>
              </view>
              <view class="action-btn pass-btn" @click.stop="handlePass(item)">
                <uni-icons type="checkbox-filled" size="18" color="#fff"></uni-icons>
                <text>通过</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-else class="empty-state">
        <image src="/static/images/empty.png" class="empty-image"></image>
        <text class="empty-text">暂无{{ currentTab === '0' ? '待审核' : '审核' }}记录</text>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading && list.length > 0" class="loading-more">
        <uni-load-more status="loading"></uni-load-more>
      </view>
    </scroll-view>

    <!-- 快速审核弹窗 -->
    <uni-popup ref="auditPopup" type="bottom" background-color="#fff">
      <view class="audit-popup">
        <view class="popup-header">
          <text class="popup-title">审核意见</text>
          <uni-icons type="closeempty" size="24" @click="closeAuditPopup"></uni-icons>
        </view>
        <view class="popup-content">
          <textarea 
            v-model="auditComment" 
            placeholder="请输入审核意见（选填）"
            class="audit-textarea"
            maxlength="200"
          ></textarea>
          <view v-if="auditType === '2'" class="inspect-goods">
            <view class="section-title">选择需要抽检的商品</view>
            <checkbox-group @change="handleGoodsChange">
              <label v-for="goods in currentGoods" :key="goods.detailId" class="goods-checkbox">
                <checkbox :value="goods.detailId" />
                <text>{{ goods.goodsName }} - {{ goods.quantity }}{{ goods.unit }}</text>
              </label>
            </checkbox-group>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-cancel" @click="closeAuditPopup">取消</button>
          <button class="btn-confirm" @click="confirmAudit">确认</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { auditAppointment, getAppointment } from '@/api/business/appointment.js'
import request from '@/utils/request'
import storage from '@/utils/storage'
import constant from '@/utils/constant'

export default {
  data() {
    return {
      searchValue: '',
      currentTab: '0', // 0-待审核 1-全部
      filterTabs: [
        { label: '待审核', value: '0', count: 0 },
        { label: '全部', value: '1', count: 0 }
      ],
      list: [],
      loading: false,
      refreshing: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      statistics: {
        pending: 0,
        today: 0,
        passed: 0
      },
      // 审核相关
      currentItem: null,
      currentGoods: [],
      auditType: '', // 1-通过 2-需抽检 3-拒绝
      auditComment: '',
      selectedGoods: [],
      // 权限控制
      userRoles: [],
      hasPermission: false
    }
  },
  onLoad() {
    console.log('页面加载，开始获取数据')
    // 先检查权限
    this.checkPermission()
    if (this.hasPermission) {
      this.loadStatistics()
      this.loadList(true)
    }
  },
  methods: {
    // 获取预约列表 - 使用正确的接口
    listAppointment(query) {
      return request({
        url: '/system/appointment/list',  // 使用 /list 而不是 /miniList
        method: 'GET',
        params: query
      })
    },

    getAuditStatusCount() {
      return request({
        url: '/system/appointment/countAuditStatus',
        method: 'GET'
      })
    },
    
    // 检查权限
    checkPermission() {
      const roles = storage.get(constant.roles) || []
      this.userRoles = roles.map(role => {
        if (typeof role === 'object' && role.roleKey) {
          return role.roleKey
        }
        return role
      })
      
      // 只有市场食品安全员才能访问预约审核
      this.hasPermission = this.userRoles.includes('market_safety_officer') || this.userRoles.includes('admin')
      
      if (!this.hasPermission) {
        uni.showModal({
          title: '权限不足',
          content: '您没有权限访问预约审核功能',
          showCancel: false,
          success: () => {
            // 返回上一页或跳转到首页
            uni.navigateBack({
              fail: () => {
                uni.switchTab({
                  url: '/pages/index'
                })
              }
            })
          }
        })
      }
      
      console.log('用户角色:', this.userRoles, '是否有权限:', this.hasPermission)
    },
    
    // 加载统计数据
    async loadStatistics() {

      const res = await this.getAuditStatusCount()
      if (res.code === 200) {
        this.statistics.pending = res.data.waitAuditCount || 0
        this.statistics.today = res.data.todayAuditCount || 0
        this.statistics.passed = res.data.passAuditCount || 0
      }
      // try {
      //   // 获取待审核数量
      //   const res = await this.listAppointment({
      //     pageNum: 1,
      //     pageSize: 1,
      //     auditStatus: '0'
      //   })
      //   if (res.code === 200) {
      //     this.statistics.pending = res.total || 0
      //     this.filterTabs[0].count = this.statistics.pending
      //   }
        
      //   // 获取今日审核数量（这里简化处理）
      //   const todayRes = await this.listAppointment({
      //     pageNum: 1,
      //     pageSize: 100
      //   })
      //   if (todayRes.code === 200) {
      //     const today = new Date().toISOString().split('T')[0]
      //     const todayList = (todayRes.rows || []).filter(item => {
      //       return item.auditTime && item.auditTime.startsWith(today)
      //     })
      //     this.statistics.today = todayList.length
          
      //     // 统计已通过数量
      //     const passedList = (todayRes.rows || []).filter(item => item.auditStatus === '1')
      //     this.statistics.passed = passedList.length
      //   }
      // } catch (error) {
      //   console.error('加载统计数据失败:', error)
      //   // 使用默认值
      //   this.statistics = {
      //     pending: 0,
      //     today: 0,
      //     passed: 0
      //   }
      // }
    },
    
    // 加载列表
    async loadList(refresh = false) {
      if (this.loading) return
      if (!refresh && !this.hasMore) return
      
      this.loading = true
      if (refresh) {
        this.pageNum = 1
        this.hasMore = true
      }
      
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        
        // 根据当前标签设置查询参数
        if (this.currentTab === '0') {
          params.auditStatus = '0'
        }
        
        // 添加搜索关键词
        if (this.searchValue) {
          params.merchantName = this.searchValue
        }
        
        console.log('请求参数:', params)
        const res = await this.listAppointment(params)
        console.log('响应数据:', res)
        
        if (res.code === 200) {
          // 数据直接在res的根级别
          const data = res.rows || []
          const total = res.total || 0
          
          console.log('解析数据:', data.length, '条，总数:', total)
          
          if (refresh) {
            this.list = data
          } else {
            this.list = [...this.list, ...data]
          }
          
          // 根据总数判断是否还有更多数据
          this.hasMore = this.list.length < total
          if (this.hasMore) {
            this.pageNum++
          }
          
          console.log('当前列表数据:', this.list.length, '条')
        } else {
          // 如果没有数据，显示空状态
          if (refresh) {
            this.list = []
          }
          this.hasMore = false
        }
      } catch (error) {
        console.error('加载列表失败:', error)
        // 显示更详细的错误信息
        let errorMsg = '加载失败'
        if (error && error.message) {
          if (error.message.includes('Network')) {
            errorMsg = '网络连接失败'
          } else if (error.message.includes('timeout')) {
            errorMsg = '请求超时'
          }
        }
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
        if (refresh) {
          this.list = []
        }
        this.hasMore = false
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadStatistics()
      this.loadList(true)
    },
    
    // 加载更多
    loadMore() {
      this.loadList()
    },
    
    // 搜索
    handleSearch() {
      this.loadList(true)
    },
    
    // 清空搜索
    handleClear() {
      this.searchValue = ''
      this.loadList(true)
    },
    
    // 切换标签
    handleTabChange(value) {
      this.currentTab = value
      this.loadList(true)
    },
    
    // 跳转详情
    goToDetail(item) {
      uni.navigateTo({
        url: `/pages/audit/detail?id=${item.applyId}`
      })
    },
    
    // 快速通过
    async handlePass(item) {
      this.currentItem = item
      this.auditType = '1'
      this.auditComment = ''
      this.$refs.auditPopup.open()
    },
    
    // 需要抽检
    async handleInspect(item) {
      // 先获取详情，获取商品列表
      try {
        const res = await getAppointment(item.applyId)
        if (res.code === 200) {
          this.currentItem = item
          this.currentGoods = res.data.appointmentDetailList || []
          this.auditType = '2'
          this.auditComment = ''
          this.selectedGoods = []
          this.$refs.auditPopup.open()
        }
      } catch (error) {
        uni.showToast({
          title: '获取商品信息失败',
          icon: 'none'
        })
      }
    },
    
    // 拒绝
    handleReject(item) {
      this.currentItem = item
      this.auditType = '3'
      this.auditComment = ''
      this.$refs.auditPopup.open()
    },
    
    // 选择商品
    handleGoodsChange(e) {
      this.selectedGoods = e.detail.value
    },
    
    // 关闭弹窗
    closeAuditPopup() {
      this.$refs.auditPopup.close()
      this.currentItem = null
      this.auditComment = ''
      this.selectedGoods = []
    },
    
    // 确认审核
    async confirmAudit() {
      if (!this.currentItem) return
      
      // 需抽检时必须选择商品
      if (this.auditType === '2' && this.selectedGoods.length === 0) {
        uni.showToast({
          title: '请选择需要抽检的商品',
          icon: 'none'
        })
        return
      }
      
      // 拒绝时必须填写原因
      if (this.auditType === '3' && !this.auditComment) {
        uni.showToast({
          title: '请填写拒绝原因',
          icon: 'none'
        })
        return
      }
      
      try {
        const data = {
          applyId: this.currentItem.applyId,
          auditStatus: this.auditType,
          auditComment: this.auditComment
        }
        
        if (this.auditType === '2') {
          data.inspectionDetailIds = this.selectedGoods
        }
        
        const res = await auditAppointment(data)
        if (res.code === 200) {
          uni.showToast({
            title: '审核成功',
            icon: 'success'
          })
          this.closeAuditPopup()
          this.loadList(true)
          this.loadStatistics()
        }
      } catch (error) {
        uni.showToast({
          title: '审核失败',
          icon: 'none'
        })
      }
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const map = {
        '0': 'pending',
        '1': 'passed',
        '2': 'inspect',
        '3': 'rejected'
      }
      return map[status] || ''
    },
    
    // 获取状态文本
    getStatusText(status) {
      const map = {
        '0': '待审核',
        '1': '已通过',
        '2': '需抽检',
        '3': '已拒绝'
      }
      return map[status] || ''
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return time.substring(5, 16) // 简单处理，显示月-日 时:分
    }
  }
}
</script>

<style scoped>
.audit-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.stat-cards {
  display: flex;
  padding: 20rpx;
  background: #fff;
}

.stat-card {
  flex: 1;
  text-align: center;
  padding: 20rpx;
}

.stat-value {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.search-box {
  background: #fff;
  padding: 0 20rpx;
}

.filter-tabs {
  display: flex;
  background: #fff;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.filter-tab {
  position: relative;
  padding: 10rpx 30rpx;
  margin-right: 30rpx;
  font-size: 28rpx;
  color: #666;
}

.filter-tab.active {
  color: #1890ff;
  font-weight: bold;
}

.filter-tab.active::after {
  content: '';
  position: absolute;
  bottom: -10rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: #1890ff;
}

.tab-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background: #ff4d4f;
  color: #fff;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 20rpx;
  min-width: 30rpx;
  text-align: center;
}

.list-container {
  height: calc(100vh - 400rpx);
}

.audit-item {
  background: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 12rpx;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.item-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.item-status {
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.item-status.pending {
  background: #fff7e6;
  color: #fa8c16;
}

.item-status.passed {
  background: #f6ffed;
  color: #52c41a;
}

.item-status.inspect {
  background: #fffbe6;
  color: #faad14;
}

.item-status.rejected {
  background: #fff1f0;
  color: #ff4d4f;
}

.item-info {
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-row {
  display: flex;
  margin-bottom: 15rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #999;
  font-size: 26rpx;
  width: 160rpx;
}

.info-value {
  color: #333;
  font-size: 26rpx;
  flex: 1;
}

.item-footer {
  display: flex;
  justify-content: end;
  flex-wrap: wrap;
  align-items: center;
  margin-top: 20rpx;
}

.submit-time {
  display: flex;
  align-items: center;
  color: #999;
  font-size: 24rpx;
}

.submit-time text {
  margin-left: 8rpx;
}

.action-buttons {
  display: flex;
  gap: 16rpx;
  margin-top: 10px;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
  transition: all 0.3s;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.action-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s;
}

.action-btn:active {
  transform: scale(0.95);
  box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.2);
}

.action-btn:active::before {
  left: 100%;
}

.action-btn text {
  color: #fff;
  position: relative;
  z-index: 1;
}

.pass-btn {
  background: linear-gradient(135deg, #52c41a, #73d13d);
}

.pass-btn:active {
  background: linear-gradient(135deg, #389e0d, #52c41a);
}

.inspect-btn {
  background: linear-gradient(135deg, #faad14, #ffc53d);
}

.inspect-btn:active {
  background: linear-gradient(135deg, #d48806, #faad14);
}

.reject-btn {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
}

.reject-btn:active {
  background: linear-gradient(135deg, #cf1322, #ff4d4f);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
  margin-top: 30rpx;
}

.loading-more {
  padding: 30rpx;
}

/* 审核弹窗 */
.audit-popup {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-content {
  padding: 30rpx;
}

.audit-textarea {
  width: 100%;
  height: 200rpx;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.inspect-goods {
  margin-top: 30rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.goods-checkbox {
  display: flex;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.goods-checkbox text {
  margin-left: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.popup-footer {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
}

.popup-footer button {
  flex: 1;
  height: 80rpx;
  font-size: 30rpx;
  border-radius: 12rpx;
  line-height: 80rpx;
  border: none;
}

.btn-cancel {
  background: #faad14;
  color: #fff;
}

.btn-confirm {
  background: #52c41a;
  color: #fff;
}
</style>